﻿#include "gyscada.h"
#include "config.h"

#include <QMessageBox>
#include<qtextcodec.h>
GYSCADA* GYSCADA::instance = NULL;

GYSCADA::GYSCADA()
{

    QTextCodec* code=QTextCodec::codecForName("utf-8");

    QTextCodec::setCodecForLocale(code);
    libgyscada_config_t config;
    config.t0 = GYSCADAConfig::getInstance()->getGyscadaT0();
    config.t1 = GYSCADAConfig::getInstance()->getGyscadaT1();
    config.t2 = GYSCADAConfig::getInstance()->getGyscadaT2();

    gyscada = libgyscada_create(&config);
    if (gyscada == NULL) {
        return;
    }

    /* Add router */
    QList<ConfigRouterItem>& routers = GYSCADAConfig::getInstance()->getRouterList();
    for (QList<ConfigRouterItem>::iterator it = routers.begin();
         it != routers.end();
         ++it) {

        QByteArray byteArrayIp = it->ip.toLatin1();
        char* ip = byteArrayIp.data();
        uint32_t* addrs = (uint32_t*)calloc(it->addrs.length(), sizeof(uint32_t));
        for (int i = 0; i < it->addrs.length(); ++i) {
            addrs[i] = it->addrs.at(i);
        }

        if (addrs != NULL) {
            if (libgyscada_control_add_client(gyscada, ip, it->port, GYSCADA::receive, NULL, addrs, it->addrs.length()) != 0) {
                QMessageBox::critical(NULL, QObject::tr("Error"),
                                      QObject::tr("Can't connect control server(%1:%2)").arg(it->ip).arg(it->port));
            }
        }
        free(addrs);
    }
}

GYSCADA::~GYSCADA()
{
    libgyscada_destroy(gyscada);
}

GYSCADA* GYSCADA::getInstance()
{
    if (GYSCADA::instance == NULL) {
        GYSCADA::instance = new GYSCADA;
    }

    return GYSCADA::instance;
}

void GYSCADA::receive(
        libgyscada_control_type_t *types, uint32_t *addrs,
        libgyscada_control_error_t *errors, uint32_t length, void *arg)
{
}

bool GYSCADA::control(
    libgyscada_control_type_t type, uint32_t addr, void *value,
    libgyscada_control_error_t *error)
{
    return libgyscada_control(gyscada, &type, &addr, &value, error, 1) == 0;
}

bool GYSCADA::control(
    libgyscada_control_type_t* types, uint32_t* addrs, void** values,
    libgyscada_control_error_t* errors, size_t length)
{
    return libgyscada_control(gyscada, types, addrs, values, errors, length) == 0;
}
